<?php
/**
 * Created by PhpStorm.
 * User: davin
 * Date: 14-10-19
 * Time: 下午12:03
 *
 * 全局设置类
 */

use LaravelBook\Ardent\Ardent;

class Setting extends Ardent{

    const GET_PATH_ACCESS_TOKEN = '/token';

    private static $instance = null;


    public static $column = array(
        'site_url' => '网站地址',
        'company_name' => '公司名称',
        'master_email' => '管理员邮件地址',
        'address' => '公司地址',
        'service_phone' => '服务电话',
        'mobile' => '手机',
        'company_instroductions' => '公司简介',
        'app_id' => 'AppID',
        'app_url' => '微信的URL地址',
        'app_secret' => 'AppSecret',
        'access_token' => 'AccessToken',
        'access_token_expires_in' => 'AccessToken 的到期时间',
        'integral_scale' => '消费赠送积分比率',
        'integral_pay_scale' => '积分结算比率(如值为100,则100积分抵1元)',
    );

    /**
     * 获取微信的Token，只有 微信认证 后才可使用获取用户OpenID功能
     * @return bool
     */
    public function getAccessToken(){
        if($this->access_token_expires_in < time()){
            $curlManager = new CurlManager();
            $curlManager->set_action('get_access_token', $this->app_url.self::GET_PATH_ACCESS_TOKEN, '');
            $curlManager->open()->get('get_access_token', array('grant_type'=>'client_credential','appid'=>$this->app_id,'secret'=>$this->app_secret));
            $result = json_decode($curlManager->body());
            if(isset($result->access_token)){
                $this->access_token = $result->access_token;
                $this->access_token_expires_in = time() + (int)$result->expires_in;
                $this->save();
            }else if(isset($result->errcode)){
                $this->errors()->add('error', $result->errmsg);
                return false;
            }else{
                $this->errors()->add('error', '未知错误');
                return false;
            }
        }
        return $this->access_token;
    }

    public static function getInstance(){
        if(is_null(self::$instance)) {
            self::$instance = self::get()->first();
        }
        return self::$instance;
    }

}